package com.karaku.karaku_collector.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.karaku.karaku_collector.LocalSetting;
import com.karaku.karaku_collector.R;
import com.karaku.karaku_collector.collector.CollectorManager;
import com.karaku.karaku_collector.collector.CollectorStateManager;
import com.karaku.karaku_collector.collector.HeartbeatManager;
import com.karaku.karaku_collector.collector.model.VideoProfile;
import com.karaku.karaku_collector.common.BaseActivity;
import com.karaku.karaku_collector.common.binder.BindView;
import com.karaku.karaku_collector.common.binder.OnClick;
import com.karaku.karaku_collector.common.binder.UIBinder;
import com.karaku.karaku_collector.keepalive.KeepAliveService;
import com.karaku.karaku_collector.util.LogUtil;
import com.karaku.karaku_collector.util.ScreenManager;
import com.karaku.karaku_collector.util.Size;
import com.karaku.karaku_collector.util.WhiteBalance;
import com.karaku.karaku_collector.util.actions.Action1;
import com.karaku.karaku_collector.view.CameraSizeSelectorView;
import com.karaku.karaku_collector.view.ConfirmView;
import com.karaku.karaku_collector.view.DirectionEdtView;
import com.karaku.karaku_collector.view.FilterEditorView;
import com.karaku.karaku_collector.view.MaskEditorView;
import com.karaku.karaku_collector.view.ProfileSelectorView;
import com.karaku.karaku_collector.view.RoomIdEdtView;
import com.karaku.karaku_collector.view.ScaleView;
import com.karaku.karaku_collector.view.StateView;

@BindView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @BindView(R.id.surface_container)
    private FrameLayout surfaceContainer;
    @BindView(R.id.mask_editor_view)
    private MaskEditorView maskEditorView;
    @BindView(R.id.btn_room_id)
    private Button btnRoomId;
    @BindView(R.id.tv_room_id)
    private TextView tvRoomId;
    @BindView(R.id.btn_direction)
    private Button btnDirection;
    @BindView(R.id.btn_start)
    private Button btnStart;
    @BindView(R.id.btn_detail)
    private Button btnDetail;
    @BindView(R.id.btn_scale)
    private Button btnScale;
    @BindView(R.id.btn_select_camera)
    private Button btnSelectCamera;
    @BindView(R.id.btn_select_profile)
    private Button btnSelectProfile;
    @BindView(R.id.btn_edit_cus_frame)
    private Button btnEditCusFrame;
    @BindView(R.id.btn_edit_filter)
    private Button btnEditFilter;
    @BindView(R.id.tv_error)
    private TextView tvError;

    @BindView(R.id.view_room_id_edt)
    private RoomIdEdtView roomIdEdtView;
    @BindView(R.id.view_direction_edt)
    private DirectionEdtView directionEdtView;
    @BindView(R.id.view_confirm)
    private ConfirmView confirmView;
    @BindView(R.id.view_state)
    private StateView stateView;
    @BindView(R.id.camera_size_selector_view)
    private CameraSizeSelectorView cameraSizeSelectorView;
    @BindView(R.id.profile_selector_view)
    private ProfileSelectorView profileSelectorView;
    @BindView(R.id.view_scale)
    private ScaleView scaleView;
    @BindView(R.id.view_filter_editor)
    private FilterEditorView filterEditorView;

    private CollectorManager.Listener collectorManagerListener = new CollectorManager.Listener() {

        @Override
        public void onOpenCameraFailed() {

        }

        @Override
        public void onNewView(SurfaceView surfaceView) {
            if (surfaceView != null) {
                surfaceContainer.removeAllViews();
                surfaceContainer.addView(surfaceView);
            }
        }

        @Override
        public void onDeleteView(SurfaceView surfaceView) {
            surfaceContainer.removeAllViews();
        }

        @Override
        public void onStartFailed() {
        }

        @Override
        public void onStateChanged(int state) {
            updateWithCollectorManagerState();
        }
    };

    CollectorStateManager.Listener collectorStateListener = new CollectorStateManager.Listener() {
        @Override
        public void onStateChanged(int state) {
            updateWithCollectorState();
        }
    };

    private ScreenManager.Listener screenListener = new ScreenManager.Listener() {
        @Override
        public void onScreenChanged(boolean isScreenOn) {
            if (!isScreenOn) {
                ScreenManager.getInstance().screenOn();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏

        super.onCreate(savedInstanceState);
        setContentView(UIBinder.bind(this));

        hideTitleBar();
        hideStatusBar();
        initView();
        CollectorStateManager.getInstance().setListener(collectorStateListener);
        CollectorManager.getInstance().setListener(collectorManagerListener);
        ScreenManager.getInstance().setListener(screenListener);

        checkStart();
    }

    private void checkStart() {
        if (CollectorManager.getInstance().getState() == CollectorManager.STATE_STARTED) {
            SurfaceView surfaceView = CollectorManager.getInstance().getSurfaceView();
            if (surfaceView != null) {
                if (surfaceView.getParent() != null) {
                    ((ViewGroup)surfaceView.getParent()).removeView(surfaceView);
                }
                surfaceContainer.removeAllViews();
                surfaceContainer.addView(CollectorManager.getInstance().getSurfaceView());
            }
        } else if (CollectorManager.getInstance().getState() == CollectorManager.STATE_STOPPED) {
            if (LocalSetting.getInstance().isStarted()) {
                surfaceContainer.post(new Runnable() {
                    @Override
                    public void run() {
                        start();
                    }
                });
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.d("LIFE", "onNewIntent");
    }

    private void initView() {
        updateBtnRoomId();
        updateBtnDirection();
        updateWithCollectorManagerState();
        updateWithCollectorState();
        updateWithProfile();
        surfaceContainer.post(new Runnable() {
            @Override
            public void run() {
                updateWithCamera();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        CollectorStateManager.getInstance().setListener(null);
//        CollectorManager.getInstance().setListener(null);
//        ScreenManager.getInstance().setListener(null);
    }

    @OnClick(R.id.btn_room_id)
    private void setRoomId() {
        roomIdEdtView.show(LocalSetting.getInstance().getRoomId(), new Action1<String>() {
            @Override
            public void run(String roomId) {
                if (!TextUtils.isEmpty(roomId)) {
                    LocalSetting.getInstance().setRoomId(roomId);
                    updateBtnRoomId();
                }
            }
        });
    }

    @OnClick(R.id.btn_direction)
    private void setDirection() {
        directionEdtView.show(LocalSetting.getInstance().getDirection(), new Action1<Integer>() {
            @Override
            public void run(Integer dir) {
                LocalSetting.getInstance().setDirection(dir);
                updateBtnDirection();
            }
        });
    }

    @OnClick(R.id.btn_start)
    private void startStop() {
        if (TextUtils.isEmpty(LocalSetting.getInstance().getRoomId())) {
            Toast.makeText(this, "请设置RoomId", Toast.LENGTH_SHORT).show();
            return;
        }
        if (LocalSetting.getInstance().getPreviewSize() == null) {
            Toast.makeText(this, "未获取到最佳相机分辨率", Toast.LENGTH_SHORT).show();
            return;
        }
        confirmView.show(CollectorManager.getInstance().isStopped() ? "确定要启动么" : "确定要停止么", new Runnable() {
            @Override
            public void run() {
                if (CollectorManager.getInstance().isStopped()) {
                    start();
                } else {
                    stop();
                }
            }
        });
    }

    @OnClick(R.id.btn_select_camera)
    private void selectCamera() {
        cameraSizeSelectorView.show(new Action1<Size>() {
            @Override
            public void run(Size size) {
                LocalSetting.getInstance().setPreviewSize(size);
                updateWithCamera();
            }
        });
    }

    @OnClick(R.id.btn_select_profile)
    private void selectProfile() {
        profileSelectorView.show(new Action1<Integer>() {
            @Override
            public void run(Integer profile) {
                LocalSetting.getInstance().setVideoProfile(profile);
                updateWithProfile();
            }
        });
    }

    @OnClick(R.id.btn_detail)
    private void detailClick() {
        if (stateView.getVisibility() == View.GONE) {
            stateView.show();
        } else {
            stateView.hide();
        }
    }

    @OnClick(R.id.btn_scale)
    private void scale() {
        maskEditorView.hideEditor();
        scaleView.show(new Action1<Float>() {
            @Override
            public void run(Float scale) {
                CollectorManager.getInstance().setScale(scale);
            }
        });
    }

    @OnClick(R.id.btn_edit_cus_frame)
    private void editCusFrame() {
        maskEditorView.showEditor();
    }

    @OnClick(R.id.btn_edit_filter)
    private void editFilter() {
        maskEditorView.hideEditor();
        filterEditorView.show(new Action1<WhiteBalance.WhiteBalanceResult>() {
            @Override
            public void run(WhiteBalance.WhiteBalanceResult arg) {

            }
        }, new Action1<Float>() {
            @Override
            public void run(Float arg) {

            }
        });
    }

    private void start() {
        CollectorManager.getInstance().start();
        HeartbeatManager.getInstance().start();
        enableHeartbeat(true);
    }

    private void stop() {
        CollectorManager.getInstance().stop();
        HeartbeatManager.getInstance().stop();
        enableHeartbeat(false);
    }

    private void enableHeartbeat(boolean enable) {
        LogUtil.d("STATE", "enableHeartbeat:" + enable);
        Intent i = new Intent(this, KeepAliveService.class);
        i.putExtra("enable_heartbeat", enable);
        startService(i);
    }

    private void updateBtnRoomId() {
        String roomId = LocalSetting.getInstance().getRoomId();
        btnRoomId.setText(TextUtils.isEmpty(roomId) ? "设置RoomId" : roomId);
        updateName();
    }

    private void updateBtnDirection() {
        btnDirection.setText(LocalSetting.getInstance().getDirection() == LocalSetting.DIR_FRONT ? "正面" : "侧面");
        updateName();
    }

    private void updateName() {
        String roomId = LocalSetting.getInstance().getRoomId();
        int direction = LocalSetting.getInstance().getDirection();
        tvRoomId.setText(String.format("%s-%s",
                TextUtils.isEmpty(roomId) ? "" : roomId,
                direction == LocalSetting.DIR_FRONT ? "正" : "侧"));
    }

    private void updateWithCollectorManagerState() {
        switch (CollectorManager.getInstance().getState()) {
            case CollectorManager.STATE_STARTED:
                btnStart.setText("停止");
                btnStart.setEnabled(true);

                btnDirection.setVisibility(View.GONE);
                btnRoomId.setVisibility(View.GONE);
                btnDetail.setVisibility(View.VISIBLE);
                btnScale.setVisibility(View.VISIBLE);
                btnSelectCamera.setVisibility(View.GONE);
                btnSelectProfile.setVisibility(View.GONE);
                btnEditCusFrame.setVisibility(View.VISIBLE);
                btnEditFilter.setVisibility(View.VISIBLE);

//                tvError.setBackgroundColor(0XFFFF0000);
                break;
            case CollectorManager.STATE_STARTING:
                btnStart.setText("启动中...");
                btnStart.setEnabled(false);

                btnDirection.setVisibility(View.GONE);
                btnRoomId.setVisibility(View.GONE);
                btnDetail.setVisibility(View.GONE);
                btnScale.setVisibility(View.GONE);
                btnSelectCamera.setVisibility(View.GONE);
                btnSelectProfile.setVisibility(View.GONE);
                btnEditCusFrame.setVisibility(View.GONE);
                btnEditFilter.setVisibility(View.GONE);

                filterEditorView.hide();
                maskEditorView.hideEditor();
                scaleView.hide();
                stateView.hide();

                tvError.setBackgroundColor(0XFFFF0000);
                break;
            case CollectorManager.STATE_STOPPED:
                btnStart.setText("启动");
                btnStart.setEnabled(true);

                btnDirection.setVisibility(View.VISIBLE);
                btnRoomId.setVisibility(View.VISIBLE);
                btnDetail.setVisibility(View.GONE);
                btnScale.setVisibility(View.GONE);
                btnSelectCamera.setVisibility(View.VISIBLE);
                btnSelectProfile.setVisibility(View.VISIBLE);
                btnEditCusFrame.setVisibility(View.GONE);
                btnEditFilter.setVisibility(View.GONE);

                filterEditorView.hide();
                maskEditorView.hideEditor();
                scaleView.hide();
                stateView.hide();

                tvError.setBackgroundColor(0X11FF0000);
                break;
        }
    }

    private void updateWithCollectorState() {
        int state = CollectorStateManager.getInstance().getState();
        LogUtil.d("STATE", "updateWithCollectorState:"+state);
        if (state == CollectorStateManager.STATE_STOPPED) {
            LogUtil.d("STATE", "updateWithCollectorState1");
            showError("未启动");
        } else if (state == CollectorStateManager.STATE_NORMAL) {
            LogUtil.d("STATE", "updateWithCollectorState2");
            hideError();
        } else {
            LogUtil.d("STATE", "updateWithCollectorState3");
            showError(CollectorStateManager.getStateName(state) + "\n" + CollectorStateManager.getInstance().getStateDescription());
        }
    }

    private void updateWithCamera() {
        FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) surfaceContainer.getLayoutParams();
        Size size = LocalSetting.getInstance().getPreviewSize();
        if (size != null) {
            p.height = surfaceContainer.getWidth() * size.width / size.height;
            surfaceContainer.setLayoutParams(p);
            btnSelectCamera.setText(String.format("相机:%d * %d", size.height, size.width));
            scaleView.setContentLayoutParams(p);
            maskEditorView.setContentLayoutParams(p);
            filterEditorView.setContentLayoutParams(p);
        }
    }

    private void updateWithProfile() {
        VideoProfile vp = VideoProfile.getProfile(LocalSetting.getInstance().getVideoProfile());
        btnSelectProfile.setText(String.format("码率: %s", vp.name));
    }

    private void showError(String text) {
        LogUtil.d("STATE", "showError:"+text);
        tvError.setText(text);
        tvError.setVisibility(View.VISIBLE);
    }

    private void hideError() {
        LogUtil.d("STATE", "hideError");
        tvError.setVisibility(View.GONE);
    }

    @Override
    protected void onBack() {
        if (roomIdEdtView.getVisibility() == View.VISIBLE) {
            roomIdEdtView.hide();
            return;
        }
        if (directionEdtView.getVisibility() == View.VISIBLE) {
            directionEdtView.hide();
            return;
        }
        if (confirmView.getVisibility() == View.VISIBLE) {
            confirmView.hide();
            return;
        }
        if (stateView.getVisibility() == View.VISIBLE) {
            stateView.hide();
            return;
        }
        if (scaleView.getVisibility() == View.VISIBLE) {
            scaleView.hide();
            return;
        }
        if (cameraSizeSelectorView.getVisibility() == View.VISIBLE) {
            cameraSizeSelectorView.hide();
            return;
        }
        if (profileSelectorView.getVisibility() == View.VISIBLE) {
            profileSelectorView.hide();
            return;
        }
        if (filterEditorView.getVisibility() == View.VISIBLE) {
            filterEditorView.hide();
            return;
        }
        super.onBack();
    }

}
